#include <func.h>

int main(int argc,char* argv[])
{
    ARGS_CHECK(argc,3);
    int sfd;
    sfd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sfd,-1,"socket");
    printf("sfd=%d",sfd);
    struct sockaddr_in seraddr;
    bzero(&seraddr,sizeof(seraddr));
    seraddr.sin_family=AF_INET;
    seraddr.sin_addr.s_addr=inet_addr(argv[1]);
    seraddr.sin_port=htons(atoi(argv[2]));
    int ret=bind(sfd,(struct sockaddr*)&seraddr,sizeof(seraddr));
    ERROR_CHECK(ret,-1,"bind");
    ret=listen(sfd,10);
    ERROR_CHECK(ret,-1,"listen");
    int newfd;
    struct sockaddr_in client_addr;
    bzero(&client_addr,sizeof(client_addr));
    socklen_t addr_len=sizeof(client_addr);
    char buf[128]={0};
    fd_set rdset,tmpset;
    FD_ZERO(&rdset);
    FD_SET(sfd,&rdset);
    FD_SET(STDIN_FILENO,&rdset);
    while(1)
    {
        memcpy(&tmpset,&rdset,sizeof(fd_set));//tmpset是传入传出参数，每次传输结束后都需要重新写入
        ret=select(11,&tmpset,NULL,NULL,NULL);
        if(FD_ISSET(sfd,&tmpset))
        {
            newfd=accept(sfd,(struct sockaddr*)&client_addr,&addr_len);
            ERROR_CHECK(newfd,-1,"accept");
            printf("client ip=%s,port=%d\n",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
            FD_SET(newfd,&rdset);
        }
        if(FD_ISSET(STDIN_FILENO,&tmpset))
        {
            bzero(buf,sizeof(buf));
            ret=read(STDIN_FILENO,buf,sizeof(buf));
            if(!ret)
            {
                printf("i want to go\n");
                break;
            }
            send(newfd,buf,strlen(buf)-1,0);
        }
        if(FD_ISSET(newfd,&tmpset))
        {
            bzero(buf,sizeof(buf));
            ret=recv(newfd,buf,sizeof(buf),0);
            ERROR_CHECK(ret,-1,"recv");
            if(!ret)
            {
                printf("byebye\n");
                FD_CLR(newfd,&rdset);
            }
            else
            {
                printf("%s\n",buf);
            }
        }
    }
    close(newfd);
    close(sfd);
    return 0;
}